import { defineStore } from "pinia";

export const useAccountStore = defineStore("changeAccountStore", {
  state: () => ({
    accountList: []
  }),
  actions: {
    addAccount(account) {
      console.log("addAccount: ", account);

      // 查找是否存在相同 token 的账号
      const existingIndex = this.accountList.findIndex(
        item => item.userInfo.token === account.userInfo.token
      );

      if (existingIndex !== -1) {
        // 如果存在，则更新该账号信息
        this.accountList[existingIndex] = {
          ...account,
          env: account.env // 更新环境
        };
      } else {
        // 如果不存在，则添加新账号
        this.accountList.push(account);
      }
    }
  },
  persist: {
    enabled: true,
    pick: ["accountList"],
    key: "account",
    storage: localStorage
  }
});
